﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Model;
using iLangl.BusinessModel.DAL;

namespace iLangl.BusinessModel.Managers
{
	public class ProductManager
	{
		#region Singelton Pattern
		private ProductManager()
		{
		}

		private static ProductManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the ProductManager.
		/// </summary>
		public static ProductManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new ProductManager();
						}
					}
				}
				return instance;
			}
		}
		#endregion

		public IList<Product> GetProducts()
		{
			return DALFacade.Instance.ProductDAL.ReadProducts();
		}

		public Product GetTPProduct(String providerId, String productId)
		{
			return DALFacade.Instance.ProductDAL.ReadTpProduct(providerId, productId);
		}

		public void RegisterTPProducts(IList<TPProduct> products)
		{
			foreach (TPProduct product in products)
			{
				RegisterNewTPProduct(product);
			}
		}

		private void RegisterNewTPProduct(TPProduct tpproduct)
		{
			Product product = DALFacade.Instance.ProductDAL.ReadProductById(tpproduct.Id);

			if (product == null)
			{
				product = DALFacade.Instance.ProductDAL.ReadProductByName(tpproduct.Name);
				tpproduct.IsApproved = false;
			}

			//If product not exists we create a new one
			if (product == null)
			{
				product = new Product();
				product.Id = tpproduct.Id;
				product.Name = tpproduct.TPProductName;
				product.Description = tpproduct.TPProductDescription;
				product.IsApproved = false;

				DALFacade.Instance.ProductDAL.AddProduct(product, null);
			}

			tpproduct.Id = product.Id;
			tpproduct.Name = product.Name;
			tpproduct.Description = product.Description;

			DALFacade.Instance.ProductDAL.AddTPProduct(tpproduct, null);

		}
	}
}
